package com.kgis.fm.access.common.service.impl;

import java.util.List;
import java.util.Map;

import com.kgis.fm.access.common.service.AbstractExecutiveAccessService;
import com.kgis.kp.common.util.Assertion;
import com.kgis.kp.common.util.ReflectionUtil;
import com.kgis.kp.common.vo.Ordering;
import com.kgis.kp.model.Model;

/**
 * 
 * @author zhxiaomiao
 * 
 */
public abstract class AbstractExecutiveAccessServiceImpl<T extends Model> extends AbstractDataAccessServiceImpl implements AbstractExecutiveAccessService<T> {

	// private Class<T> clazz; can be used instead of using
	// ReflectionUtil.getGenericType(this.getClass());

	protected String namespace;

	public AbstractExecutiveAccessServiceImpl() {
		namespace = this.getNamespaceClass().getSimpleName();
	}

	private Class<?> getNamespaceClass() {
		return ReflectionUtil.getGenericType(this.getClass());
	}

	public Map<String, Object> appendParamters(Map<String, Object> parameter) {
		return parameter;
	}

	/** create */
	public T create(T model) {
		return (T) this.getIbatisDataAccessObject().create(this.getNamespace(), model);
	}

	/** update */
	public T update(T model) {
		return (T) this.getIbatisDataAccessObject().update(this.getNamespace(), model);
	}

	/** remove */
	public T remove(T model) {
		return (T) this.getIbatisDataAccessObject().remove(this.getNamespace(), model);
	}

	public T save(T model) {
		if (model.beNew()) {
			this.create(model);
		} else {
			this.update(model);
		}
		return model;
	}

	/** find */
	public List<T> findAll(Ordering ordering) {
		return this.getIbatisDataAccessObject().findAll(this.getNamespace(), ordering);
	}

	public List<T> findAll() {
		return this.findAll(null);
	}

	@SuppressWarnings("unchecked")
	public T findById(long id) {
		Assertion.isPositive(id, "id is not positive, id=" + id);
		return (T) this.getIbatisDataAccessObject().findById(this.getNamespace(), id);
	}

	/**
	 * @return the namespace
	 */
	public String getNamespace() {
		return namespace;
	}
}
